package com.wlcorp.forcazamis.dao.pi.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibatis.dao.client.DaoException;
import com.wlcorp.forcazamis.dao.pi.IPifittingDAO;
import com.wlcorp.forcazamis.domain.pi.Pifitting;
import com.wlcorp.forcazamis.exception.ServiceException;

public class PifittingDAOImpl extends HibernateDaoSupport implements
		IPifittingDAO {

	@SuppressWarnings("unchecked")
	public List getPifittingList(final Pifitting pifitting) throws DaoException {
		final StringBuffer queryString = new StringBuffer("select pifitting from Pifitting as pifitting where 1=1 and pifitting.deleteFlag=false");
		if(null != pifitting.getPiid()){
			queryString.append(" and pifitting.pidetail.piid = ").append(pifitting.getPiid());
		}
		queryString.append(" order by pifitting.orderNo asc");
		return getHibernateTemplate().executeFind(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = session.createQuery(queryString.toString());
				if(null != pifitting && null != pifitting.getMinRownum()){
					query.setFirstResult(pifitting.getMinRownum());
					query.setMaxResults(pifitting.getNumPerPage());
				}
				return query.list();
			}
			
		});
	}

	public Pifitting getPifittingById(Long fittingId) throws DaoException {
		return (Pifitting)getHibernateTemplate().get(Pifitting.class,fittingId);
	}

	public void deletePifitting(Pifitting pifitting) throws DaoException {
		pifitting.setDeleteFlag(true);
		getHibernateTemplate().update(pifitting);
	}

	public void savePifitting(Pifitting pifitting) throws DaoException {
		getHibernateTemplate().saveOrUpdate(pifitting);
//		getHibernateTemplate().flush();
//		getHibernateTemplate().clear();
	}

	@SuppressWarnings("unchecked")
	public List getPifittingListByPidetailId(Long piid) throws ServiceException {
		return getHibernateTemplate()
				.find("from Pifitting as pifitting where 1=1 and pifitting.deleteFlag=false and pifitting.pidetail.piid ="+ piid);
	}
}
